package com.txby.common.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.txby.common.annomapper.GjLogger;
import com.txby.common.annomapper.MybatisBaseDaoCRUD;
import com.txby.common.data.CommonApiModelMapExt;
import com.txby.common.data.ConstantErrCode;
import com.txby.common.utils.IPUtils;
import com.txby.common.utils.RedisUtils;
import com.txby.common.utils.util.ChkUtil;
import com.txby.common.utils.util.HttpToolUtil;
import com.txby.common.utils.util.Times;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.txby.core.entity.UserAppToken;

@SuppressWarnings("all")
public class CommonController {
    @Autowired
    public MybatisBaseDaoCRUD mBaseDao;
    @Autowired
    private RedisUtils redisUtils;
    public boolean isTokenValid;// 是否token有效
    public boolean isAdmin;// 是否管理员
    public CommonApiModelMapExt mm = new CommonApiModelMapExt(ConstantErrCode.CODE_0.getCode(), ConstantErrCode.CODE_0.getInfo());
    
    public static String apiUserId = "";// 用户id
    public String userToken = "";// 当前token
    public String apiTokenCachName = "apiTokenCachName-";// 当前token
    public Map reParamTypeMap = new HashMap() {{// 当前请求类型  0:web,1:android,2:iphone3:微信wechat
        put(0, "web");
        put(1, "android");
        put(2, "iphone");
        put(3, "wechat");
    }};// 当前请求类型Map  0:web,1:android,2:iphone3:微信
    public Integer reParamType;// 当前请求类型  0:web,1:android,2:iphone3:微信
    public String clientIP = "";// 当前IP
    public String requestMethod = "";// 当前请求方法
    public String tempTableName = "";// in查询时超过1000创建的临时表名
    public boolean isGlobaltempTable = true;//是全局（所有会话）还是本地（当前会话）

    public String userAgent = "";//用户代理头
    public String errmsg = "";//提示信息
    public Integer errcode = 0;//0为正常，其他失败
    public String info;//开发内部提示信息
    public String msg;//提示信息
    public Integer code;//1为正常，其他失败
    public Integer expires;//有效期秒
    public String cacheTreeData = "cacheTreeData";//
    
    private HttpServletRequest request;
    private HttpServletResponse response;

    private static Logger logger = LoggerFactory.getLogger(CommonController.class);

    /**
     * 上传单文件（文件name参数名file）,按日期hh:mmss:sss命名 code 4017: 上传出现异常 4018:
     * 上传文件大小受限制（不能超过2M） 4019:文件格式受限制（支持gif、png、jpg、bmp）
     *
     * @param request
     * @param savePath
     * @return
     */

    public Map fileUpload(HttpServletRequest request, String savePath) {
        Map m = new HashMap();
        m.put(CommonApiModelMapExt.ERRCODE, 4017);
        m.put(CommonApiModelMapExt.CODE, 4017);
        m.put(CommonApiModelMapExt.ERRMSG, "上传出现异常");
        m.put(CommonApiModelMapExt.MSG, "上传出现异常");
        m.put(CommonApiModelMapExt.INFO, "上传出现异常");
        m.put("url", "");
        try {
            Date date = new Date();
            String newName = Times.getDateToStringHHmmssSSS(date);// 自定义文件名字
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            CommonsMultipartFile orginalFile = (CommonsMultipartFile) multipartRequest
                    .getFile("tradingCertificatePicFile");// 表单中对应的文件名；
            if (orginalFile != null && !orginalFile.isEmpty()) {
                String fileName = orginalFile.getOriginalFilename();
                String suffix = fileName.substring(fileName.indexOf("."));// 获得后缀名

                long size = orginalFile.getSize();
                /*
                 * if(orginalFile.getSize()>6024*2000){ m.put("code", "4018");
                 * m.put("info","图片上传文件大小受限制（不能超过2M）"); m.put("msg",
                 * "图片不能大于2M"); return m; }
                 */

                if (!suffix.equals(".bmp") && !suffix.equals(".gif") && !suffix.equals(".png")
                        && !suffix.equals(".jpg")) {
                    m.put("code", "4019");
                    m.put("info", "文件格式受限制（支持gif、png、jpg、bmp）");
                    m.put("msg", "上传格式应为gif、png、jpg、bmp");
                    m.put(CommonApiModelMapExt.ERRCODE, 4019);
                    m.put(CommonApiModelMapExt.CODE, 4019);
                    m.put(CommonApiModelMapExt.ERRMSG, "文件格式受限制（支持gif、png、jpg、bmp）");
                    m.put(CommonApiModelMapExt.MSG, "文件格式受限制（支持gif、png、jpg、bmp）");
                    m.put(CommonApiModelMapExt.INFO, "文件格式受限制（支持gif、png、jpg、bmp）");
                    return m;
                }
                fileName = newName + suffix;
                File file = new File(savePath);
                if (!file.exists()) {// 判断文件夹是否存在，不存在就根据上面的路径创建文件夹
                    file.mkdirs();
                }
                String realpath = request.getSession().getServletContext().getRealPath(savePath);// 给予存储路径
                File f = new File(realpath + File.separator + fileName);
                String url = savePath + fileName;// 获得相对路径
                FileUtils.copyInputStreamToFile(orginalFile.getInputStream(), f);// 获取文件，并按照路径保存

                m.put(CommonApiModelMapExt.ERRCODE, 0);
                m.put(CommonApiModelMapExt.CODE, 1);
                m.put(CommonApiModelMapExt.ERRMSG, "上传成功");
                m.put(CommonApiModelMapExt.MSG, "上传成功");
                m.put(CommonApiModelMapExt.INFO, "上传成功");
                m.put("url", url);
                m.put("date", date);
                return m;
            }

        } catch (Exception e) {
            e.printStackTrace();

            return m;
        }

        return m;
    }


    
	/** 
	* @Title: chekUserAppToken  检查用户接口token是否正确
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param userName
	* @param @param token
	* @param @return    设定文件 
	* @return CommonApiModelMapExt    返回类型 
	* @throws 
	*/
	public CommonApiModelMapExt chekUserAppToken(String userName, String token) {
		CommonApiModelMapExt mm= new CommonApiModelMapExt(ConstantErrCode.CODE_4501.getCode(), ConstantErrCode.CODE_4501.getInfo());
		UserAppToken uat=(UserAppToken) this.mBaseDao.findBySqlUniqueObject("select * from "+this.mBaseDao.tableName(UserAppToken.class)+" where userName='"+userName+"'", UserAppToken.class, null);
		if(uat!=null) {
			if(!ChkUtil.isEmpty(uat.getToken())&&uat.getToken().equals(token)) {
				mm.setErrcode(ConstantErrCode.CODE_0.getCode());
				mm.setErrmsg(ConstantErrCode.CODE_0.getInfo());
				isTokenValid=true;
			}else {
				isTokenValid=false;
			}
			if(chekTokenIsAdmin(uat.getUserName())) {
//				mm.put("isAdmin", 1);
				isAdmin=true;
			}else {
				isAdmin=false;
			}
		}else {
			isTokenValid=false;
		}
		return mm;
	}
	/**
	 * 是否admin账号
	* @Title: chekTokenIsAdmin 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param userName
	* @param @return    设定文件 
	* @return boolean    返回类型 
	* @throws
	 */
	private boolean chekTokenIsAdmin(String userName) {
		userName=userName==null?"":userName;
		return  userName.equals("admin");
	}

    public CommonApiModelMapExt chekTokenCahceValid(Integer type, String token) {
/*		if(true){
			isTokenValid = true;
//		apiUserId = data[0];// 用户id
			userToken = token;// 当前token
			reParamType = type;// 当前请求类型（须）0：web,1:app
			this.springEhcacheUtil.put(apiTokenCachName, apiUserId + "_token", token);
			return new CommonApiModelMapExt(0,"token正常", null, null, null) ;
			
		}*/
        if (type == null || !reParamTypeMap.containsKey(type)) {
            isTokenValid = false;
            apiUserId = "";// 用户id
            userToken = "";// 当前token
            reParamType = null;// 当前请求类型// 0:web,1:android,2:iphone
//			return writeReturnJson(SERVER_ERR.CODE_1.getCode(), "验证失败,参数不正确", "验证失败,参数不正确");
            return new CommonApiModelMapExt(4000, "type验证失败,参数类型不正确", null, null, null);
        } else {
            try {
                String[] data = token.split("_");
                System.out.println(data.toString());
                if (data.length < 2) {
                    isTokenValid = false;
                    apiUserId = "";// 用户id
                    userToken = "";// 当前token
                    reParamType = null;// 当前请求类型（须）0：web,1:app
                    return new CommonApiModelMapExt(4001, "token验证失败,格式不正确", null, null, null);
                } else {
                    apiUserId = data[0];// 用户id
                    String oldtoken = (String) redisUtils.get( apiTokenCachName+apiUserId + "_token");
                    if (ChkUtil.isEmpty(oldtoken)) {
                        isTokenValid = false;
                        apiUserId = "";// 用户id
                        userToken = "";// 当前token
                        reParamType = null;// 当前请求类型（须）0：web,1:app
                        return new CommonApiModelMapExt(4002, "token验证失效,请重新登录验证", null, null, null);
                    }

                    if (!oldtoken.equals(token)) {
                        isTokenValid = false;
                        apiUserId = "";// 用户id
                        userToken = "";// 当前token
                        reParamType = null;// 当前请求类型（须）0：web,1:app
                        return new CommonApiModelMapExt(4003, "token验证失效，用户已在其他设备登录,请重新登录验证", null, null, null);
                    } else {
                        isTokenValid = true;
                        apiUserId = data[0];// 用户id
                        userToken = token;// 当前token
                        reParamType = type;// 当前请求类型（须）0：web,1:app
                        this.redisUtils.set(apiTokenCachName+apiUserId + "_token", token);
                        return new CommonApiModelMapExt(0, "token正常", null, null, null);
                    }
                }
            } catch (Exception e) {
                isTokenValid = false;
                apiUserId = "";// 用户id
                userToken = "";// 当前token
                reParamType = null;// 当前请求类型（须）0：web,1:app
                e.printStackTrace();
                saveLog("传入的token异常，可能格式不正确");
                return new CommonApiModelMapExt(5000, "token正常", null, null, null);
            }

        }

    }

    public CommonApiModelMapExt chekLoginOutTokenCahceValid(Integer type, String token) {
		/*		if(true){
			isTokenValid = true;
//		apiUserId = data[0];// 用户id
			userToken = token;// 当前token
			reParamType = type;// 当前请求类型（须）0：web,1:app
			this.springEhcacheUtil.put(apiTokenCachName, apiUserId + "_token", token);
			return new CommonApiModelMapExt(0,"token正常", null, null, null) ;
			
		}*/
        if (type == null || !reParamTypeMap.containsKey(type)) {
            isTokenValid = false;
            apiUserId = "";// 用户id
            userToken = "";// 当前token
            reParamType = null;// 当前请求类型// 0:web,1:android,2:iphone
//			return writeReturnJson(SERVER_ERR.CODE_1.getCode(), "验证失败,参数不正确", "验证失败,参数不正确");
            return new CommonApiModelMapExt(4000, "type验证失败,参数类型不正确", null, null, null);
        } else {
            try {
                String[] data = token.split("_");
                if (data.length < 2) {
                    isTokenValid = false;
                    apiUserId = "";// 用户id
                    userToken = "";// 当前token
                    reParamType = null;// 当前请求类型（须）0：web,1:app
                    return new CommonApiModelMapExt(4001, "token验证失败,格式不正确", null, null, null);
                } else {
                    apiUserId = data[0];// 用户id
                    String oldtoken = (String) redisUtils.get(apiTokenCachName+ apiUserId + "_token");
                    if (ChkUtil.isEmpty(oldtoken)) {
                        isTokenValid = false;
                        apiUserId = "";// 用户id
                        userToken = "";// 当前token
                        reParamType = null;// 当前请求类型（须）0：web,1:app
                        return new CommonApiModelMapExt(4002, "token验证失效,请重新登录验证", null, null, null);
                    }

                    if (!oldtoken.equals(token)) {
                        isTokenValid = false;
                        apiUserId = "";// 用户id
                        userToken = "";// 当前token
                        reParamType = null;// 当前请求类型（须）0：web,1:app
                        return new CommonApiModelMapExt(4003, "token验证失效，用户已在其他设备登录,请重新登录验证", null, null, null);
                    } else {
                        isTokenValid = true;
                        apiUserId = data[0];// 用户id
                        userToken = token;// 当前token
                        reParamType = type;// 当前请求类型（须）0：web,1:app
                        return new CommonApiModelMapExt(0, "token正常", null, null, null);
                    }
//						isTokenValid = true;
//						apiUserId = data[0];// 用户id
//						userToken = token;// 当前token
//						reParamType = type;// 当前请求类型（须）0：web,1:app
//						return new CommonApiModelMapExt(0,"token正常", null, null, null) ;
                }
            } catch (Exception e) {
                isTokenValid = false;
                apiUserId = "";// 用户id
                userToken = "";// 当前token
                reParamType = null;// 当前请求类型（须）0：web,1:app
                e.printStackTrace();
                saveLog("传入的token异常，可能格式不正确");
                return new CommonApiModelMapExt(5000, "token正常", null, null, null);
            }

        }

    }

    public CommonApiModelMapExt chekTypeValid(Integer type) {
        if (type == null || !reParamTypeMap.containsKey(type)) {
            isTokenValid = false;
            apiUserId = "";// 用户id
            userToken = "";// 当前token
            reParamType = null;// 当前请求类型// 0:web,1:android,2:iphone
            return new CommonApiModelMapExt(4000, "type验证失败,参数类型不正确", null, null, null);
        } else {
            isTokenValid = true;
            reParamType = type;
            return new CommonApiModelMapExt(0, "正常", null, null, null);
        }
    }

    public Map tokenNotValid(CommonApiModelMapExt map) throws IOException {
        if (!this.isTokenValid) {
            map.clear();
            map = new CommonApiModelMapExt(1, "token异常", null, null, null);
        } else {
            map = new CommonApiModelMapExt(1, "token正常", null, null, null);
        }
        return map;
    }


    /**
     * 存放token缓存，默认token,存活1小时，间隔1小时内有效
     *
     * @param key
     * @param value
     */
    /*
     * public void putTokenCache(String key,String value){
     * this.springEhcacheUtil.put(apiTokenCachName, key, value); }
     */
    public void putTokenCache(String CachName, String key, String value) {
        this.redisUtils.set(CachName+key, value);
    }

    /**
     * 用户手动日志保存(格式)
     *
     * @param message
     */
    public void saveLog(String message) {
        if (isTokenValid) {
            GjLogger.getLogger(GjLogger.class).log(GjLogger.getTxbyLoggerLevel(), "触发时间：" + Times.getTimes() + "，IP:" + clientIP + ",请求参数类型" + reParamType + ",请求方法类型"
                    + requestMethod + ",用户：" + apiUserId + "" + "，信息说明：" + message + "");
			/*logger.warn("触发时间：" + Times.getTimes() + "，IP:" + clientIP + ",请求参数类型" + reParamType + ",请求方法类型"
					+ requestMethod + ",用户：" + apiUserId + "" + "，信息说明：" + message + "");*/
        } else {
		/*	logger.warn("触发时间：" + Times.getTimes() + "，IP:" + clientIP + ",请求参数类型" + reParamType + ",请求方法类型"
					+ requestMethod + "，信息说明：" + message + "");*/

            GjLogger.getLogger(GjLogger.class).log(GjLogger.getTxbyLoggerLevel(), "触发时间：" + Times.getTimes() + "，IP:" + clientIP + ",请求参数类型" + reParamType + ",请求方法类型"
                    + requestMethod + "，信息说明：" + message + "");
        }
    }


    /**
     * @param sqlId
     * @return
     * @Description:sql in条件查询拆分
     */
    public static String getSplitInSql(String[] sqlId) {
        String sql = "";
        for (String str : sqlId) {
            sql += "'" + str + "',";
        }
        if (!ChkUtil.isEmpty(sql)) {
            sql = sql.substring(0, sql.length() - 1);
        }
        return sql;
    }

    /**
     * @param sqlId
     * @return
     * @Description: sql in条件查询拆分
     */
    public static String getSplitInSql(Set<String> sqlId) {
        String sql = "";
        for (String str : sqlId) {
            sql += "'" + str + "',";
        }
        if (!ChkUtil.isEmpty(sql)) {
            sql = sql.substring(0, sql.length() - 1);
        }
        return sql;
    }

    /**
     * @param sqlId
     * @return
     * @Description: 保存数据表中，外键id的“，”分割的拆分
     */
    public static String getSplitNewString(String[] sqlId) {
        String sql = "";
        for (String str : sqlId) {
            sql += str + ",";
        }
        if (!ChkUtil.isEmpty(sql)) {
            sql = sql.substring(0, sql.length() - 1);
        }
        return sql;
    }

    /**
     * @param sqlId
     * @return
     * @Description: 保存数据表中，外键id的“，”分割的拆分
     */
    public static String getSplitNewString(Set<String> sqlId) {
        String sql = "";
        for (String str : sqlId) {
            sql += str + ",";
        }
        if (!ChkUtil.isEmpty(sql)) {
            sql = sql.substring(0, sql.length() - 1);
        }
        return sql;
    }


    /**
     * @param tempTableName
     * @return
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public String getUniqueTempTableName(String tempTableName) {
        String pre = isGlobaltempTable ? "##temp_" : "#temp_";
        String suf = "" + new Date().getTime();
        tempTableName = tempTableName == null ? pre + suf : pre + tempTableName + suf;
        return tempTableName;
    }

    @ModelAttribute
    public void initUserRequest(HttpServletRequest request) throws IOException {
//		 reParamTypeMap=new HashMap() ;// 当前请求类型  0:web,1:android,2:iphone3:微信wechat
//		 put(0, "web");
//		 put(1, "android");
//		 put(2, "iphone");
//		 put(3, "wechat");
        String userAgent = request.getHeader("user-agent");
        userAgent = userAgent.toUpperCase();
        if (userAgent.contains("ANDROID")) {
            this.userAgent = "ANDROID";
        } else if (userAgent.contains("IPHONE")) {
            this.userAgent = "IPHONE";
        } else if (userAgent.contains("CHROME")) {
            this.userAgent = "CHROME";
        } else if (userAgent.contains("GECKO")) {
            this.userAgent = "GECKO";
        }
        this.request = request;
        this.response = response;
        this.requestMethod = request.getMethod().toUpperCase();
        try {
            this.clientIP = IPUtils.getIpAddr(request);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * http请求返回json
     *
     * @param httpUrl
     * @param httpType
     * @param maps
     * @return
     * @throws IOException
     */
    public String getHttpResponseContent(String httpUrl, String httpType, Map<String, String> maps) throws IOException {
        String responseContent = HttpToolUtil.getInstance().sendHttpCustom(httpUrl, httpType, maps, false, null);
        return responseContent;
    }


    /**
     * 反转List 集合数据
     *
     * @param @param  fullRegion
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: getDeviceHosInfoByRegionListReveseString
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public static String getDeviceHosInfoByRegionListReveseString(List<String> fullRegion) {
        String regionName = "";
        int size = fullRegion != null ? fullRegion.size() : 0;
        for (int i = size - 1; i >= 0; i--) {
            if (i != 0) {
                regionName += fullRegion.get(i) + "-";
            } else {
                regionName += fullRegion.get(i);
            }
        }
        return regionName;
    }

    /**
     * 处理like查询条件的通配及sql注入
     *
     * @param @param  containStr
     * @param @param  fieldName
     * @param @return 设定文件
     * @return Map    返回类型
     * @throws
     * @Title: getLikeSTransferSql
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public static Map getLikeSTransferSql(String containStr, String fieldName) {
        String sql = "";
        String fieldValue = "";
        if (!ChkUtil.isEmptyAllObject(containStr)) {
            String paramFieldName = fieldName.contains(".") ? fieldName.substring(fieldName.lastIndexOf(".") + 1, fieldName.length()) : fieldName;
            if (containStr.contains("%") || containStr.contains("_")) {
                containStr = containStr.trim().replace("%", "\\%").replace("_", "\\_");
                containStr = "%" + containStr + "%";
                sql += " and " + fieldName + " like #{pojo." + paramFieldName + "} escape '\\'  ";
            } else {
                containStr = "%" + containStr + "%";
                sql += " and " + fieldName + " like #{pojo." + paramFieldName + "} ";
            }
            fieldName = paramFieldName;
        } else {

            return null;
        }

        Map data = new HashMap();
        data.put("fieldName", fieldName);
        data.put("fieldValue", containStr);
        data.put("sql", sql);
        return data;
    }

	/**
	 * 
	 * 	Map m=new HashMap();
		m.put("ip", ip);
		m.put("port", port);
		m.put("dbname", dbname);
		return m;
	* @Title: getJdbcInfoByJdbcUrl 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param jdbcurl
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	public static Map<String,String> getJdbcInfoByJdbcUrl(String jdbcurl){
		String ip="";
		String port="";
		String dbname="";
		Map m=new HashMap();
		if(ChkUtil.isEmpty(jdbcurl)) {
			m.put("ip", ip);
			m.put("port", port);
			m.put("dbname", dbname);
			return m;
		}
		jdbcurl=jdbcurl.toLowerCase().trim();
		if(jdbcurl.startsWith("jdbc:sqlserver")){
			if(jdbcurl.indexOf("//")!=-1&&jdbcurl.indexOf(";")!=-1&&jdbcurl.lastIndexOf("=")!=-1) {
				if((jdbcurl.indexOf("//")+2<jdbcurl.indexOf(";"))) {
					String ipprot=jdbcurl.substring(jdbcurl.indexOf("//")+2,jdbcurl.indexOf(";"));
					String[] ipprotArrays =ipprot.split(":");
					if(ipprotArrays.length>1) {
						ip=ipprotArrays[0];
						port=ipprotArrays[1];
					}
				}
				if(jdbcurl.lastIndexOf("=")+1<jdbcurl.length()) {
					dbname=jdbcurl.substring(jdbcurl.lastIndexOf("=")+1);
				}
			}
		}else if(jdbcurl.startsWith("jdbc:mysql")){
			if(jdbcurl.indexOf("//")!=-1&&jdbcurl.lastIndexOf("/")!=-1) {
				if(jdbcurl.indexOf("//")+2<jdbcurl.lastIndexOf("/")) {
					String ipprot=jdbcurl.substring(jdbcurl.indexOf("//")+2,jdbcurl.lastIndexOf("/"));
					String[] ipprotArrays =ipprot.split(":");
					if(ipprotArrays.length>1) {
						ip=ipprotArrays[0];
						port=ipprotArrays[1];
					}
				}
			}
			
			if(jdbcurl.lastIndexOf("/")+1<(jdbcurl.lastIndexOf("?")!=-1?jdbcurl.lastIndexOf("?"):jdbcurl.length())) {
				dbname=jdbcurl.substring(jdbcurl.lastIndexOf("/")+1,jdbcurl.lastIndexOf("?")!=-1?jdbcurl.lastIndexOf("?"):jdbcurl.length());
			}
			
		} else if(jdbcurl.startsWith("jdbc:oracle:thin")){
			if(jdbcurl.indexOf("@")+1!=-1&&jdbcurl.lastIndexOf(":")!=-1) {
				if(jdbcurl.indexOf("@")+1<jdbcurl.lastIndexOf(":")) {
					String ipprot=jdbcurl.substring(jdbcurl.indexOf("@")+1,jdbcurl.lastIndexOf(":"));
					String[] ipprotArrays =ipprot.split(":");
					if(ipprotArrays.length>1) {
						ip=ipprotArrays[0];
						port=ipprotArrays[1];
					}
				}
			}
			if(jdbcurl.lastIndexOf(":")+1<jdbcurl.length()) {
				dbname=jdbcurl.substring(jdbcurl.lastIndexOf("/")+1,jdbcurl.lastIndexOf("?")!=-1?jdbcurl.lastIndexOf("?"):jdbcurl.length());
				dbname=jdbcurl.substring(jdbcurl.lastIndexOf(":")+1);
			}
	    }
	
		m.put("ip", ip);
		m.put("port", port);
		m.put("dbname", dbname);
		return m;
	}
 
	public static String  getJdbcDriverClassNameByJdbcUrl(String jdbcurl){
		jdbcurl=jdbcurl.toLowerCase().trim();
		String driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
		if(jdbcurl.startsWith("jdbc:sqlserver")){
			driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
		}else if(jdbcurl.startsWith("jdbc:mysql")){
			 driverClassName="com.mysql.jdbc.Driver";
		} else if(jdbcurl.startsWith("jdbc:oracle:thin")){
			  driverClassName="oracle.jdbc.driver.OracleDriver";
		}else {
			 driverClassName="org.postgresql.Driver";
		}
		return driverClassName;
	}
	

}
